/*
 * @Date: 2022-09-15 19:49:30
 * @LastEditTime: 2023-02-13 17:17:46
 * @Description: 基础路由页面
 */
import { computed, defineComponent, KeepAlive, nextTick, onMounted, reactive, ref, Suspense, Transition, watch } from "vue";
import { useUserStore } from '@/store/modules/user';
import { useRouterStore } from '@/store/modules/router';
import { useRoute, useRouter } from "vue-router";
import { useSocketStore } from '@/store/modules/socket'
import { isEmpty } from "@/utils/common"
import { ElLoading, ElMessage, ElMessageBox } from "element-plus";
import customSlots from "@/slots"
import axios from "@/axios";
import HomeTabs from "@/views/common/HomeTabs";
import classes from "./index.module.scss";
import titlePng from "@/assets/logo.png";
import audio from "@/assets/audio/notice.mp3";
import defaultAvatar from "@/assets/img/avatar_default.png"
import MenuItem from '@/components/MenuItem'
import MyForm from "@/components/MyForm";
import { Bell, BellFilled, CaretBottom, Expand, Fold, PictureFilled, QuestionFilled, SwitchButton } from "@element-plus/icons-vue";
export default defineComponent({
    components: { HomeTabs, MenuItem, MyForm },

    setup() {
        /**
        * 弹窗页面引用
        * @type {Ref<UnwrapRef<{}>>}
        */
        const xUpdate = ref();
        /**
         * 弹窗引用
         * @type {Ref<UnwrapRef<{}>>}
         */
        const xModal = ref();
        const audioRef = ref();
        const menuScroll = ref()
        const userStore = useUserStore();
        const routerStore = useRouterStore();
        const socketStore = useSocketStore();

        /**
         * @description: 获取系统消息
         * @return {*}
         */
        const getXtxx = () => new Promise((resolve, reject) => {
            axios.post({
                sjdx: { dxdm: "SYS_PTGL_XTXX" }, sys: { cllx: "select" }, page: { pageSize: 5 }, yobj: { ydzt: "0" }
            }).then((res: any) => {
                if (res.code === 200) {
                    if (res.data.list && res.data.list.length > 0) {
                        resolve(res.data.list)
                    } else {
                        resolve([])
                    }
                } else {
                    resolve([])
                }
            }).catch(err => {
                reject(err)
            })

        })

        /**
         * @description: 初始化系统消息
         * @return {*}
         */
        const initXtxx = () => {
            getXtxx().then((res: any) => {
                myData.xtxx = res
                //初始化socket
                socketStore.initSocket();
                //订阅socketStore
                socketStore.$onAction(({ name, args }: any) => {
                    //监听receiveMsg方法
                    if (name === 'receiveMsg' && args[0] && args[0].mdd === 'SYS_PTGL_XTXX') {
                        audioRef.value.play();
                        if (myData.xtxx.unshift(args[0]) > 5) {
                            myData.xtxx.pop()
                        }
                        if (args[0].xxlb === '00') {
                            getXtxx().then((resopnse: any) => {
                                myData.xtxx = resopnse
                            })
                        }
                    }
                })

            })

        }
        const xtxxClick = async (item?: any) => {
            axios.post({
                sjdx: {
                    "dxdm": "SYS_PTGL_XTXX"
                },
                sys: {
                    "cllx": "dxjcxx"
                },
            }).then(async res => {
                myData.tcckProps.title = "消息提醒"
                myData.tcckShow = true
                await nextTick()
                await nextTick()
                if (item) {
                    //标记已读
                    axios.post({
                        sjdx: {
                            "dxdm": "SYS_PTGL_XTXX"
                        },
                        sys: {
                            "cllx": "update"
                        },
                        yobj: {
                            id: item.id,
                            ydzt: '1'
                        }
                    }).then((res1: any) => {
                        if (res1.code === 200) {
                            //重新获取xtxx
                            getXtxx().then((response: any) => {
                                myData.xtxx = response
                            })
                            xUpdate.value.initPage(res.data, 'dxjcxx', null, item);
                        }
                    })
                }
                else {
                    xUpdate.value.initPage(res.data, 'select');
                }
            })
        }
        const myHelpClick = async (id?: any) => {
            axios.post({
                sys: {
                    authCode: "QTQX_WDGL",
                    cllx: "dxjcxx"
                },
            }).then(async res => {
                myData.tcckProps.title = "系统文档"
                myData.tcckShow = true
                await nextTick()
                await nextTick()
                xModal.value.maximize()
                xUpdate.value.initPage(res.data, 'ckwd', null, { ckwd: id });
            })
        }

        const myData = reactive({
            xtmc: userStore.getCurrentSystemName,
            zxyh: userStore.getSys.zxyhs,
            myHelp: undefined as string | undefined,
            sysList: [] as any,
            /**
             * 菜单列表
             */
            menuList: [],
            xtxx: [] as any[],
            props: {
                label: "mc",
                isLeaf: "leaf",
            },
            sysListVisible: false,
            isCollapse: ref(false),
            currentRouteName: "",
            titlePng: "",
            //弹出窗口是否展示
            tcckShow: false,
            tcckKey: 0,
            tcckProps: {
                /**
                 * 弹出窗口标题
                 */
                title: "",
                width: "80%",
                height: "80%",
            },
            icon: "",
        });
        const router = useRouter();
        const route = useRoute();
        document.title = userStore.getCurrentSystemName

        /**
         * 获取系统列表
         */
        const loadNode = () => {
            if (useRouterStore().getSysList.length > 0) {
                let currentSYS: any = {}
                myData.sysList = useRouterStore().getSysList.filter((item: any) => {
                    if (item.dm == userStore.getCurrentSystemCode) {
                        currentSYS = item
                    }
                    return item.dm !== userStore.getCurrentSystemCode
                })
                let kzxxJSON = JSON.parse(currentSYS.kzxx)
                if (kzxxJSON.xttx) {
                    myData.titlePng = axios.getBaseURL() +
                        "/default?sjdx.dxdm=SYS_QX_QTQX&sys.cllx=download&yobj.id=" + kzxxJSON.xttx
                } else {
                    myData.titlePng = "error"
                }
                if (kzxxJSON.myHelp) {
                    myData.myHelp = kzxxJSON.myHelp
                } else {
                    myData.myHelp = undefined
                }

                if (currentSYS.mc) {
                    document.title = currentSYS.mc;
                    myData.xtmc = currentSYS.mc
                    userStore.setCurrentSystemName(currentSYS.mc)
                } if (currentSYS.dm) {
                    userStore.setCurrentSystemCode(currentSYS.dm)
                }
            }

        }
        /**
         * 菜单树
         * @type {ComputedRef<{}>}
         */
        const menuTree = computed(() => {
            nextTick(() => {
                setTimeout(() => {
                    menuScroll.value.update()
                }, 300)
            })
            return routerStore.getMenuTree;
        })
        watch(() => route.path, () => {
            myData.currentRouteName = route.name as string;
        }, { immediate: true, deep: true });

        /**
         * 用户信息
         * @type {ComputedRef<{}>}
         */
        const user = computed(() => {
            return userStore.getUser;
        })
        /**
         * 用户头像
         * @type {ComputedRef<unknown>}
         */
        const userImg: any = computed(() => {
            if (userStore.getUser.tx) {
                return axios.getBaseURL() + "/default?sjdx.dxdm=SYS_QX_QTQX&sys.cllx=download&yobj.id=" + userStore.getUser.tx
            }
        })

        /**
         * @description: 用户节点生成
         * @param {*} computed
         * @return {*}
         */
        const userVNode = computed(() => {
            return (
                <div style="display:flex;align-items:center;background:#ffffffaa;border-radius:5px;padding:5px;">
                    <div style="padding-right:10px">
                        <div style="font-size:14px;color:#409eff;text-align:right">
                            {user.value.yhxm}
                        </div>
                        {user.value.jgxx ?
                            <div style="font-size:12px;padding-top:2px;color:#909399;text-align:right">
                                {user.value.jgxx.jgmc}
                            </div> : null}
                    </div>
                    <el-image
                        class={classes.userImg}
                        src={userImg.value ? userImg.value : defaultAvatar}
                        fit="cover"
                        v-slots={{
                            error: () => {
                                return (<el-icon style="font-size:24px;display:block;padding:6px"><PictureFilled /></el-icon>)
                            }
                        }}
                    ></el-image>
                    <el-popover width={200}
                        placement="bottom-end"
                        trigger="hover"
                        v-slots={{
                            reference: () => {
                                return <el-badge is-dot={myData.xtxx.length > 0}>
                                    <el-icon style="padding-left:10px;"><Bell /></el-icon>
                                </el-badge>
                            }
                        }}
                    >
                        <div style="border-bottom: 1px solid #f0f0f0;display:flex;align-items:center;justify-content:space-between;">
                            <div style="font-size:14px;">
                                <el-icon><BellFilled /></el-icon>
                                <span style="padding-left:4px">消息提醒</span>
                            </div>
                            <el-button size="small" link type='primary' onclick={() => xtxxClick()} >更多</el-button>
                        </div>
                        <div style="padding-top:4px">
                            {myData.xtxx.length > 0 ? myData.xtxx.map((item: any, index: number) => {
                                return <div> <el-link onClick={() => xtxxClick(item)}> {item.xxnr}</el-link></div>
                            }) : <el-empty image-size={100} description="暂无未读消息"></el-empty>}
                        </div>
                    </el-popover>
                    {!isEmpty(myData.myHelp) ? <el-tooltip content="系统文档" placement="bottom">
                        <el-link icon={QuestionFilled} onClick={() => myHelpClick(myData.myHelp)} underline={false} style="padding-left:10px;padding-right:10px" />
                    </el-tooltip> : null}
                    <el-icon class={classes.logout} onClick={logout}><SwitchButton /></el-icon>
                </div>
            )
        })

        /**
         * 用户退出操作
         */
        const logout = () => {
            ElMessageBox.confirm(
                '你确定要退出吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                userStore.logout()
            }).catch(() => { })
        }

        /**
         * @description: 切换系统
         * @param {any} item
         * @return {*}
         */
        const checkSys = async (item: any) => {
            let loading = ElLoading.service({ text: '数据请求中！', background: 'rgba(0,0,0,0.6)' });
            myData.sysListVisible = false
            myData.xtmc = item.mc
            document.title = item.mc
            if(item.ssyydz){
                //根据系统配置设置对应的所属应用地址
                axios.setBaseURL(item.ssyydz);
                socketStore.close();
                socketStore.initSocket();
            }
            userStore.setCurrentSystemCode(item.dm)
            userStore.setCurrentSystemName(item.mc)
            await routerStore.setRouter()
            loading.close()
            router.replace(routerStore.getIndex(routerStore.getMenuTree[0]))
            loadNode()
        }

        /**
         * @description: 左侧菜单伸缩改变
         * @return {*}
         */
        const collapseChange = () => {
            myData.isCollapse = !myData.isCollapse
        }

        /**
         * 弹窗页面回调
         */
        const fromClose = () => {
            myData.tcckShow = false
        }


        const menuChange = () => {
            nextTick(() => {
                setTimeout(() => {
                    menuScroll.value.update()
                }, 300)
            })
        }


        const ggcx = () => {
            axios.post({
                sys: { authCode: "QTQX_WDGL", cllx: "select" },
                yobj: { yxx: "1", sfsxjg: "0", lb: "02", ckwd: "1" }
            }).then((response) => {
                if (response.status && response.data.list.length > 0 && response.data.list[0].id) {
                    axios.post({
                        sys: {
                            authCode: "QTQX_WDGL",
                            cllx: "dxjcxx"
                        },

                    }).then(async res => {
                        myData.tcckProps.title = "公告展示"
                        myData.tcckShow = true
                        console.log(xUpdate.value)
                        await nextTick()
                        await nextTick()
                        xUpdate.value.initPage(res.data, 'ggzs', null, { ggzs: response.data.list[0].id });
                    })
                }
            })

        }

        onMounted(() => {
            loadNode()
            initXtxx()
            ggcx()
        })



        return {
            route,
            checkSys,
            myData,
            menuTree,
            user,
            userVNode,
            userImg,
            logout,
            loadNode,
            collapseChange,
            fromClose,
            xUpdate,
            xModal,
            menuChange,
            audioRef,
            menuScroll
        }
    },
    render() {
        return (
            <div class={classes.homeBody}>
                <audio hidden ref="audioRef" controls src={audio} ></audio>
                <el-container>
                    <el-header class={classes.homeHeard}>
                        <div class={classes.heardTitle}>
                            <div class={classes.titleSpan}>
                                {!isEmpty(this.myData.titlePng) ? <el-image
                                    style="width:32px;height:32px;margin-right:10px"
                                    src={this.myData.titlePng}
                                    fit="cover"
                                    v-slots={{
                                        error: () => {
                                            return (<img style="width:32px;height:32px;display:block" src={titlePng} />)
                                        }
                                    }}
                                ></el-image> : null}
                                <div>{this.myData.xtmc}
                                </div>
                                {!isEmpty(this.myData.zxyh) ?
                                    <div style="font-size:12px;color:#909399;padding:8px 0 0 4px">在线用户:{this.myData.zxyh}</div>
                                    : null}
                            </div>
                            <div class={classes.userInfo}>
                                {this.userVNode}
                                {this.myData.sysList.length > 0 ? <el-popover v-model={[this.myData.sysListVisible,'visible']} trigger="click" placement="bottom"
                                  v-slots={{
                                      reference: () => {
                                          return (<div style="font-size:12px;cursor: pointer;">其他系统<el-icon><CaretBottom /></el-icon></div>
                                          )
                                      },
                                  }
                                  }
                                >
                                    <div>
                                        {this.myData.sysList.map((item: any) => {
                                            return <div class={classes.sysLink} onClick={() => this.checkSys(item)}>{item.mc}</div>
                                        })}
                                    </div>
                                </el-popover> : null}
                            </div>
                        </div>
                    </el-header>
                    <el-container>
                        <el-aside class={classes.homeAside} style={this.myData.isCollapse ? "width: 64px;" : "width: 210px;"}>
                            <el-scrollbar ref="menuScroll" noresize class={classes.elScrollbar} >
                                <el-menu
                                    onOpen={this.menuChange}
                                    onClose={this.menuChange}
                                    class={classes.myMenu}
                                    collapse={this.myData.isCollapse}
                                    default-active={this.myData.currentRouteName}
                                >
                                    {this.menuTree.map((item: any, index: number) => {
                                        return <MenuItem item={item}></MenuItem>
                                    })}
                                </el-menu>
                            </el-scrollbar>
                            <div class={classes.collapse} onClick={this.collapseChange}>
                                {this.myData.isCollapse ? <el-icon class={classes.collapseIcon}><Expand /></el-icon> : <div class={classes.collapseTitle}> <el-icon class={classes.collapseIcon}><Fold /></el-icon><span class={classes.collapseText}>收起菜单</span></div>}
                            </div>
                        </el-aside>
                        <el-container>
                            <el-main>
                                <div class={classes.contentBox} style={this.myData.isCollapse ? "left: 64px;" : "left: 210px;"}>
                                    <HomeTabs></HomeTabs>
                                    <div class={classes.content}>
                                        <el-scrollbar id="main-container" noresize style="height:100%">
                                            <router-view v-slots={{
                                                default: (scope: any) => {
                                                    if (scope.Component)
                                                        return <KeepAlive><Suspense>{scope.Component}</Suspense></KeepAlive>
                                                }
                                            }}></router-view>
                                        </el-scrollbar>
                                    </div>
                                </div>
                            </el-main>
                        </el-container>
                    </el-container>
                </el-container>
                <Suspense>
                    <vxe-modal transfer ref="xModal" v-model={this.myData.tcckShow} {...this.myData.tcckProps}
                        show-zoom resize>
                        <MyForm ref="xUpdate" slots={customSlots} onClose={this.fromClose}></MyForm>
                    </vxe-modal>
                </Suspense>
            </div >
        )
    }
})
